import router, { asyncRoutes } from './router'
import store from '@/store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // 白名单
// const whiteList = ['/login'] // no redirect whitelist
// 登陆了,不能能去登录页
// 没登录,只能去登录页
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  // console.log(token)
  if (token) {
    // 登陆了
    if (to.path === '/login') {
      //去登录页
      // 中断要跳转/login这次导航重新跳转到/
      next('/')
      NProgress.done()
    } else {
      // 去别的页面
      next()
      if (!store.getters.name) {
        const menus = await store.dispatch('user/userInfoActions') // 返回的menus数组
        const filterName = asyncRoutes.filter(routerObj => {
          // console.log(routerObj.children[0].name)
          const routeName = routerObj.children[0].name.toLowerCase() // 动态路由的八个name
          return menus.includes(routeName)
        })

        filterName.push({ path: '*', redirect: '/404', hidden: true })
        //  知识点:路由切换匹配的路由规则对象数组存在于内存中
        router.addRoutes(filterName)
        // 给vuex也存一封:
        store.commit('permission/setRoutes', filterName)
        next({
          path: to.path,
          replace: true
        })
      }
    }
  } else {
    // 没有登陆
    if (whiteList.includes(to.path)) {
      // 要去的路由地址字符串是否在白名单里出现
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  // 正常next()放行了跳转了,才会走后置守卫,关闭正常流程进度条

  document.title = getPageTitle(to.meta.title)
  NProgress.done()
})
